package com.example.shop.common.config;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.AnonymousCredentialProvider;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.core.http.HttpClient;
import com.aliyun.core.http.ProxyOptions;
import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.KeyManager;
import javax.net.ssl.X509TrustManager;
import java.net.InetSocketAddress;
import java.time.Duration;

@Configuration
public class SMSConfig {
    /**
     * @value 装配失败的原因：
     *  变量被关键字static修饰
     *  类没有使用@Component及其衍生标签修饰
     *  在Bean初始化时构造方法中引用被@Value修饰的变量
     */
    @Value(value = "${sms.access-key-id}")
    private String ACCESS_KEY_ID;
    @Value(value = "${sms.access-key-secret}")
    private String ACCESS_KEY_SECRET;

    @Bean
    public AsyncClient smsAsyncClient(){

        HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
                .connectionTimeout(Duration.ofSeconds(10)) //设置连接的超时时间，默认是10秒
                .responseTimeout(Duration.ofSeconds(10)) //设置响应超时时间，默认是20秒
                .maxConnections(32) //连接池的大小，即连接数
                .maxIdleTimeOut(Duration.ofSeconds(60))//设置连接池超时时间，默认为30秒
                .ignoreSSL(true)//如果是https连接，您需要配置证书，或者忽略证书(.ignoreSSL(true))
                .build();

        //配置凭证认证信息，包括ak、secret、token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(ACCESS_KEY_ID)
                .accessKeySecret(ACCESS_KEY_SECRET)
                .build());

        //配置java异步短信发送客户端
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") //设置请求的短信服务器的区域标识id。
                .httpClient(httpClient)
                .credentialsProvider(provider)
                //客户端级的配置重写，可以设置端点，Http请求参数等。
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                        .setEndpointOverride("dysmsapi.aliyuncs.com")
                ).build();

        return client;
    }

}
